app.controller('accountingcontroller', ['$scope', '$parse', '$http', function($scope, $parse, $http)
{
	$scope.isComponentLoading = true;
	$scope.servicebase = '../../Core/server.class.php';

	/*
	* Set a range of date to display operations
	*/
	$scope.setRangeDate = function()
	{
		var now = new Date();
		var year = now.getFullYear();
		var month = now.getMonth();
		$scope.startDate = new Date(year, month - 1, 20);
		$scope.endDate = new Date(year, month + 1, 10);
		/*
		$("#rangeSelector").jqxRangeSelector(
		{
                width: 750, 
				height: 15, 
				moveOnClick: true,
				min: new Date(year, 0, 1),
				max: new Date(year, 11, 31), 
				labelsOnTicks: false, 
				range: { from: $scope.startDate, to: $scope.endDate },
                majorTicksInterval: "month", 
				minorTicksInterval: "month", 
				labelsFormat: 'MMM', 
				markersFormat: 'M/y'
        });
		*/
	}
	
	/*
	* The range of date changed
	*/
	$('#rangeSelector').on('change', function () 
	{ 
		var range = $('#rangeSelector').jqxRangeSelector('getRange');
		var startdate = range.from;
		var enddate = range.to;
		$scope.refreshOperationsCommand(startdate, enddate);
	});
	
	/*
	* Selection on the categories treeview
	*/
	$('#jqxTree').bind('select', function (event) 
	{
		var args = event.args;
		var item = $('#jqxTree').jqxTree('getItem', args.element);
		//alert('jqxTree');
		$scope.$apply(function () 
		{
			console.info("SelectedItem from jqxTree changed");
			$scope.selectedItem = item;
			if($scope.selectedItem !== null)
			{	
				$('#alert').show();
				$scope.isCategorySelected = true;
			}
			else
			{
				$scope.isCategorySelected = false;
			}
		});
	});
	
	/*
	* Build the tree
	*/
	$scope.buildData = function(data) 
	{
		console.info("buildData - called"); 
		console.info("buildData - start"); 
		var startTime = new Date();
		var source = [];
		var items = [];
		// build hierarchical source.
		for (i = 0; i < data.length; i++) {
			var item = data[i];
			var label = item["Name"];
			var parentid = item["ParentCategory"];
			var id = item["Id"];

			if (items[parentid]) {
				var item = { parentid: parentid, label: label, item: item, id: id };
				if (!items[parentid].items) {
					items[parentid].items = [];
				}
				items[parentid].items[items[parentid].items.length] = item;
				items[id] = item;
			}
			else {
				items[id] = { parentid: parentid, label: label, item: item, id: id };
				source[id] = items[id];
			}
		}
		var endTime = new Date();
		var timeDiff = endTime - startTime;
		console.info("buildData - finished => " + timeDiff + " ms");
		return source;
	};
	
	/*
	* Delete account process
	*/
	$scope.deleteAccountCommand = function()
	{
		console.info("deleteAccountCommand - called"); 	
		
		if($scope.selectedaccount != '')
		{
			$scope.url = '../../Core/BonoHomeCore/Services/deleteAccountClient.php'; 
		
			console.info("deleteAccountCommand - call deleteAccountClient with accountName : " + $scope.selectedaccount.Name); 
		
			$scope.deleteAccount = function() 
			{
				$http.post($scope.url, { "accountName" : $scope.selectedaccount.Name}).
				success(function(data, status) 
				{
					console.info("deleteAccountCommand - call success"); 
					$scope.refreshAccountsCommand();
					$scope.status = status;
					$scope.data = data;
					$scope.result = data; 
					
					if($scope.data.isFailed == true)
					{
						$scope.setMessageCommand($scope.data.exception, 'danger');
					}
					else
					{
						$scope.canAddAccount = false;
						$scope.canDeleteAccount = false;
						$scope.canAddCategory = false;
						$scope.canListOperations = false;
						$scope.setMessageCommand($scope.Accounting_Message_DeletedAccount, "success");
					}
				})
				.
				error(function(data, status) 
				{
					console.error("deleteAccountCommand - call failed"); 	
					$scope.data = data || "Request failed";
					$scope.status = status;		
					$scope.setMessageCommand($scope.Accounting_Message_DeletedAccountFailed, "danger");
					console.error("deleteAccountCommand - data : " + $scope.data); 						
				});
			};
			
			$scope.deleteAccount();
		}
	};
	
	/*
	* Define the changed account process
	*/
	$scope.selectedaccountchanged = function() 
	{
		console.info("selectedaccountchanged - called"); 
		
		if($scope.selectedaccount != undefined)
		{
			$scope.canDeleteAccount = true;
			$scope.canAddAccount = true;
			$scope.canAddCategory = true;
			$scope.canCreateBalance = true;
			$scope.canListOperations = true;
			$scope.canAddOperation = true;
			
			$scope.refreshOperationsCommand();
			$scope.refreshCategoriesCommand();
			//$scope.synchronizeCategoriesAndFoldersCommand();
		}
		else
		{
			$scope.canDeleteAccount = false;
			$scope.canAddAccount = false;
			$scope.canCreateBalance = false;
			$scope.canAddCategory = false;
			$scope.canAddOperation = false;
			$scope.canListOperations = false;
			$scope.operations = [];
		}
	};
	
	/*
	* Prepare to change the account
	*/
	$scope.editAccountCommand = function()
	{
		$scope.editAccountName = $scope.selectedaccount.Name;
		$scope.editAccountState = $scope.accountStates[$scope.selectedaccount.State];
		$("#editAccount").modal('show');
	}
	
	/*
	* Update an account
	*/
	$scope.updateAccountCommand = function()
	{	
		console.info("updateAccountCommand - called");
		
		$scope.url = '../../Core/BonoHomeCore/Services/updateAccountClient.php'; 
		
		var state = $scope.accountStates.indexOf($scope.editAccountState); 
		
		console.info("updateAccountCommand - call updateAccountClient with accountName : " + $scope.editAccountName + " accountState : " + state); 
			
		$http.post($scope.url, { "accountId": $scope.selectedaccount.Id, "accountName": $scope.editAccountName, "accountState": state }).
		success(function(data, status) 
		{	
			console.info("updateAccountCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.setMessageCommand("Compte mis à jour.","success");
				$("#editAccount").modal('hide');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("updateAccountCommand - call failed"); 	
			$scope.setMessageCommand("Mise à jour de compte en échec.", 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;		
			console.error("updateAccountCommand - data : " + $scope.data);		
		});
	}
	
	/*
	* Get balance command
	*/
	$scope.getBalanceCommand = function()
	{
		console.info("getBalanceCommand - called");
		
		$scope.url = '../../Core/BonoHomeCore/Services/addAccountClient.php'; 
		
		var state = $scope.accountStates.indexOf($scope.newAccountState); 
		
		console.info("addAccountCommand - call addAccountClient with accountName : " + $scope.newAccountName + " accountState : " + state); 
			
		$http.post($scope.url, { "accountName": $scope.newAccountName, "accountState": state }).
		success(function(data, status) 
		{	
			console.info("addAccountCommand - call success"); 
			//Refresh accounts
			$scope.refreshAccountsCommand();
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			$("#addAccount").modal('hide');
		})
		.
		error(function(data, status) 
		{
			console.error("addAccountCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;		
			console.error("addAccountCommand - data : " + $scope.data);		
		});
	}
	
	/*
	* Define add account process
	*/
	$scope.addAccountCommand = function() 
	{
		console.info("addAccountCommand - called");
		$scope.canAddAccount = false;
		var state = $scope.accountStates.indexOf($scope.newAccountState); 
		
		console.info("addAccountCommand - call addAccountClient with accountName : " + $scope.newAccountName + " accountState : " + state); 

		$http.post($scope.servicebase, { "service" : "addAccount", "state": state, "name": $scope.newAccountName }).
		success(function(data, status) 
		{	
			console.info("addAccountCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			console.info(JSON.stringify(data));
			
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.refreshAccountsCommand();
				$scope.setMessageCommand("Compte ajouté.","success");
				$("#addAccount").modal('hide');
			}
			$scope.canAddAccount = true;
		})
		.
		error(function(data, status) 
		{
			console.error("addAccountCommand - call failed"); 	
			$scope.setMessageCommand("Création de compte en échec.", 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;		
			$scope.canAddAccount = true;
			console.error("addAccountCommand - data : " + $scope.data);		
		});
	};
	
	/*
	* Define refresh operations process
	*/
	$scope.refreshOperationsCommand = function(startdate, enddate) 
	{
		if(startdate == null || startdate == '')
		{
			var now = new Date();
			var year = now.getFullYear();
			var month = now.getMonth();
			startdate = new Date(year, month, 1);
		}
		
		if(enddate == null || enddate == '')
		{
			enddate =  new Date();
			var now = new Date();
			var year = now.getFullYear();
			var month = now.getMonth();
			enddate = new Date(year, month + 1, 1);
		}
		
		startdate = startdate.toLocaleFormat('%Y/%m/%d');
		enddate =  enddate.toLocaleFormat('%Y/%m/%d');
	
		console.info("refreshOperationsCommand - called");
		
		$scope.loadingOperations = true;
		$scope.canSelectOperation = false;
		$scope.expectedTotal = 0;
		$scope.realTotal = 0;
		$scope.credits = [];
		$scope.debits = [];
		$scope.operationsStatus = "Mise à jour des opérations";
		$scope.operations = [];

		console.info("refreshOperationsCommand - call getOperationsClient with accountName : " + $scope.selectedaccount.Id + " /start date  : " + startdate + " /end date : " + enddate); 

		$http.post($scope.servicebase, { "service" : "getOperations", "accountId": startdate.toString(), "startDate": startdate.toString(), "endDate": enddate.toString() }).
		success(function(data, status) 
		{
			console.info("refreshOperationsCommand - call success"); 
			$scope.loadingOperations = false;
			$scope.canSelectOperation = true;
			$scope.status = status;
			$scope.operationsStatus = "Operations à jour";
			$scope.data = data;
			$scope.result = data;
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.operations = data.response;
				$scope.operations.forEach(function(operation) 
				{
					//Is a credit
					if(operation.Type == '0')
					{
						$scope.credits.push(operation);
						$scope.expectedTotal += parseInt(operation.Expectedamount);
						$scope.realTotal += parseInt(operation.Realamount);
					}
					else
					{
						$scope.debits.push(operation);
						$scope.expectedTotal -= parseInt(operation.Expectedamount);
						$scope.realTotal -= parseInt(operation.Realamount);
					}
					
					operation.Status = $scope.operationStates[operation.Status];
					operation.PaymentMean = $scope.operationPaymentMeans[operation.PaymentMean];
				});
			}
		})
		.
		error(function(data, status) 
		{
			console.error("refreshOperationsCommand - call failed"); 	
			$scope.operationsStatus = "Erreur dans la mise à jour des opérations";
			$scope.loadingOperations = false;
			$scope.canSelectOperation = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("refreshOperationsCommand - data : " + $scope.data);		
		});
	}
	
	/*
	* Set the bill
	*/
	$scope.setBill = function(files)
	{
		$scope.Bill = files[0];
	}

	/*
	* Define add operation process
	*/
	$scope.addOperationCommand = function() 
	{
		console.info("addOperationCommand - called");
	
		$scope.url = '../../Core/BonoHomeCore/Services/addOperationClient.php'; 
		
		var state = $scope.operationStates.indexOf($scope.newOperationState); 
		var paymentMean = $scope.operationPaymentMeans.indexOf($scope.newOperationPaymentMean); 
		var operationDate = $('#newDateOperationControl').val();
		var operationType = ($scope.newOperationType == null || $scope.newOperationType == '') ? false : true;
		var operationIsRecurring = ($scope.newOperationIsRecurring == null || $scope.newOperationIsRecurring == '') ? false : true;

		console.info("addOperationCommand - call addOperationClient with accountName : " + $scope.selectedaccount.Name);
		
		$http.post($scope.url, { "accountId": $scope.selectedaccount.Id, "newOperationLabel": $scope.newOperationLabel, "newOperationType": operationType, "newOperationState": state, "newOperationCategory": $scope.newOperationCategory, "newOperationPaymentMean": paymentMean,  "newOperationExpectedamount": $scope.newOperationExpectedamount.replace(",", "."), "newOperationDate": operationDate, "newOperationIsRecurring": operationIsRecurring}).
		success(function(data, status) 
		{
			console.info("addOperationCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'warning');
			}
			else
			{
				if($scope.Bill != null)
				{
					$scope.attachBillToOperationCommand(data.response.Id);
				}
				$scope.refreshOperationsCommand();
				$("#addOperation").modal('hide');
				$scope.setMessageCommand('Opération ajoutée.', 'success');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("addOperationCommand - call failed"); 	
			$scope.setMessageCommand('Ajout d\'une opération en échec.', 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;				
			console.error("addOperationCommand - data : " + $scope.data);			
		});
	};
	
	/*
	* Attach a bill on an operation
	*/
	$scope.attachBillToOperationCommand = function(idOperation)
	{
		console.info("attachBillToOperationCommand - called");
	
		$scope.url = '../../Core/BonoHomeCore/Services/attachBillToOperationClient.php'; 
		
		console.info("attachBillToOperationCommand - call attachBillToOperationClient with id operation : " + idOperation);
		
		var fd = new FormData();
		fd.append("file", $scope.Bill);
		fd.append("idOperation", idOperation);
		
		$http.post($scope.url,
			fd,
			{ 
				withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
			}
		).
		success(function(data, status) 
		{
			console.info("attachBillToOperationCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'warning');
			}
			else
			{
				$scope.setMessageCommand('Facture jointe.', 'success');
			}
			$scope.Bill = null;
		})
		.
		error(function(data, status) 
		{
			console.error("attachBillToOperationCommand - call failed"); 	
			$scope.setMessageCommand('Ajout d\'une facture en échec.', 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;				
			console.error("attachBillToOperationCommand - data : " + $scope.data);			
		});
	}
	
	/*
	* Open the bill
	*/
	$scope.openBillCommand = function(bin)
	{
		console.info("openBillCommand - called");
		var aFileParts = ['<p>' + bin + '</p>'];
		var blob = new Blob(aFileParts, {type : 'text/html'});
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
	}
	
	/*
	* Define refresh accounts process
	*/
	$scope.refreshAccountsCommand = function() 
	{
		console.info("refreshAccountsCommand - called");
		
		$scope.accounts = [];

		$scope.loadingAccounts = true;
		$scope.canSelectAccount = false;
		
		$http.post($scope.servicebase, { "service" : "getAccounts"}).
		success(function(data, status) 
		{
			console.info("refreshAccountsCommand - call success"); 
			$scope.loadingAccounts = false;
			$scope.canSelectAccount = true;
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if(data.isFailed)
			{
				$scope.setMessageCommand(data.exception, 'danger');
			}
			else
			{
				$scope.accounts = data.response;
			}
		})
		.
		error(function(data, status) 
		{
			console.error("refreshAccountsCommand - call failed"); 	
			$scope.loadingAccounts = false;
			$scope.canSelectAccount = false;
			$scope.data = data || "Request failed";
			$scope.status = status;
			console.error("refreshAccountsCommand - data : " + $scope.data);		
		});
	}
	
	/*
	* Refresh categories 
	*/
	$scope.refreshCategoriesCommand = function() 
	{
		console.info("refreshCategoriesCommand - called");
		
		$scope.loadingCategories = true;
		$scope.categories = [];

		console.info("refreshCategoriesCommand - call getCategoriesClient with Id account : " + $scope.selectedaccount.Id);

		$http.post($scope.servicebase, { "service" : "getCategories", "accountName": $scope.selectedaccount.Id }).
		success(function(data, status) 
		{	
			console.info("refreshCategoriesCommand - call success"); 
			$scope.loadingCategories = false;
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.categories = data.response;
				var source = $scope.buildData(data.response);
				$scope.loadingCategories = false;
				$('#jqxTree').jqxTree({ allowDrag:true, allowDrop:true, source: source, width: '100%', height: '250px'});
				
				$scope.categoryView = [];
		
				$scope.categories.forEach(function(category) 
				{
					var operationList = [];
					
					$scope.operations.forEach(function(operation) 
					{
						if(category.Id == operation.Category)
						{
							operationList.push(operation);
						}
					});
					if(operationList.length > 0)
					{
						var obj = new categoryOperation(category.Id, category.Name, operationList);
						$scope.categoryView.push(obj);
					}
					
					
				});
				$scope.drawChartCommand();
			}
		})
		.
		error(function(data, status) 
		{
			console.error("refreshCategoriesCommand - call failed"); 
			$scope.loadingCategories = false;
			$scope.data = data || "Request failed";
			$scope.status = status;	
			console.error("refreshCategoriesCommand - data : " + $scope.data);		
		});
	}
	
	/*
	* Cancel the category selection
	*/
	$scope.cancelSelectedCategoryCommand = function()
	{
		console.info("cancelSelectedCategoryCommand - called");
		$('#alert').hide();
		$("#jqxTree").jqxTree('selectItem', null);
		$scope.selectedItem = null;
	}
	
	/*
	* Add a new category
	*/
	$scope.addCategoryCommand = function(id) 
	{
		console.info("addCategoryCommand - called");
	
		$scope.url = '../../Core/BonoHomeCore/Services/addCategoryClient.php'; 
		
		var parentCategory = 0;
		
		$scope.loadingCategories = true;

		if($scope.selectedItem !== null && $scope.selectedItem !== '')
		{
			parentCategory = $scope.selectedItem.id;
		}
		
		console.info("addCategoryCommand - call addCategoryClient with accountName : " + $scope.selectedaccount.Name + " newCategoryName " + $scope.newCategoryName + " parentCategory " + parentCategory);

		$http.post($scope.url, { "accountName" : $scope.selectedaccount.Name, "newCategoryName" : $scope.newCategoryName, "parentCategory" : parentCategory}).
		success(function(data, status) 
		{
			console.info("addCategoryCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.newCategoryName = '';
				$scope.refreshCategoriesCommand();
			}
		})
		.
		error(function(data, status) 
		{
			console.error("addCategoryCommand - call failed"); 
			$scope.data = data || "Request failed";
			$scope.status = status;		
			console.error("addCategoryCommand - data : " + $scope.data);						
		});
	}
	
	/*
	* Delete the selected category
	*/
	$scope.deleteCategoryCommand = function(id)
	{
		console.info("deleteCategoryCommand - called");
	
		$scope.loadingCategories = true;
		$scope.url = '../../Core/BonoHomeCore/Services/deleteCategoryClient.php'; 
		
		console.info("deleteCategoryCommand - call deleteCategoryClient with categoryId : " + id);
		
		$http.post($scope.url, { "categoryId" : id }).
		success(function(data, status) 
		{
			console.info("deleteCategoryCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.refreshCategoriesCommand();
				$scope.cancelSelectedCategoryCommand();
			}
		})
		.
		error(function(data, status)
		{
			console.error("deleteCategoryCommand - call failed"); 
			$scope.data = data || "Request failed";
			$scope.status = status;	
			console.error("deleteCategoryCommand - data : " + $scope.data);					
		});
	}
	
	/*
		Delete the operation
	*/
	$scope.deleteOperationCommand = function(id)
	{
		console.info("deleteOperationCommand - called");
		
		$scope.url = '../../Core/BonoHomeCore/Services/deleteOperationClient.php'; 

		console.info("deleteOperationCommand - call deleteOperationClient with operationId : " + id);
		
		$http.post($scope.url, { "operationId" : id }).
		success(function(data, status) 
		{
			console.info("deleteOperationCommand - call success"); 
			//Refresh accounts
			$scope.refreshOperationsCommand();
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.setMessageCommand('Opération supprimée.', 'success');
			}
		})
		.
		error(function(data, status) 
		{
			console.info("deleteOperationCommand - call failed"); 
			$scope.data = data || "Request failed";
			$scope.status = status;			
			$scope.setMessageCommand('Erreur lors de la suppression de l\'opération.', 'danger');
			console.error("deleteOperationCommand - data : " + $scope.data);			
		});
	}
	
	/*
		Open the modal in order to update the operation
	*/
	$scope.selectToModifyOperationCommand = function(operation)
	{
		console.info("selectToModifyOperationCommand - called");
		$scope.selectedOperation = operation;
		$scope.newOperationLabel = operation.Label;
		$scope.newOperationState = operation.Status;
		
		var index = 0;
		$scope.categories.forEach(function(category) 
		{
			if(category.Id == operation.Category)
			{
				return false;
			}
			else
			{
				index++;
			}
		});
	
		$scope.newOperationCategory = $scope.categories[index];
		$scope.newOperationExpectedamount = operation.Expectedamount;
		$scope.newOperationRealamount = operation.Realamount;
		$scope.newOperationDate = operation.Operationdate;
		$scope.newOperationPaymentMean = operation.PaymentMean;
	}
	
	/*
		Update the operations
	*/
	$scope.updateOperationCommand = function()
	{
		console.info("updateOperationCommand - called");
		
		$scope.url = '../../Core/BonoHomeCore/Services/updateOperationClient.php';
		
		var state = $scope.operationStates.indexOf($scope.newOperationState); 
		var paymentMean = $scope.operationPaymentMeans.indexOf($scope.newOperationPaymentMean); 
		var operationDate = $('#modifyDateOperationControl').val();
		var operationType = ($scope.newOperationType == null || $scope.newOperationType == '') ? false : true;
		var operationIsRecurring = ($scope.newOperationIsRecurring == null || $scope.newOperationIsRecurring == '') ? false : true;		
			
		console.info("updateOperationCommand - call updateOperationClient");
		
		$http.post($scope.url, { "accountName": $scope.selectedaccount.Name, "idOperation": $scope.selectedOperation.Id, "newOperationLabel": $scope.newOperationLabel, "newOperationType": operationType, "newOperationState": state, "newOperationCategory": $scope.newOperationCategory.Name, "newOperationPaymentMean": paymentMean,  "newOperationExpectedamount": $scope.newOperationExpectedamount, "newOperationRealamount": $scope.newOperationRealamount, "newOperationDate": operationDate, "newOperationIsRecurring": operationIsRecurring}).
		success(function(data, status) 
		{
			console.info("updateOperationCommand - call success"); 
			//Refresh accounts
			$scope.refreshOperationsCommand();
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'warning');
			}
			else
			{
				if($scope.Bill != null)
				{
					$scope.attachBillToOperationCommand(data.response.Id);
				}
				$scope.refreshOperationsCommand();
				$scope.drawChartCommand();
				$("#modifyOperation").modal('hide');
				$scope.setMessageCommand('Opération mise à jour.', 'success');
			}
		})
		.
		error(function(data, status) 
		{
			console.info("updateOperationCommand - call failed"); 
			$scope.data = data || "Request failed";
			$scope.status = status;			
			$scope.setMessageCommand('Mise à jour de l\'opération en échec.', 'danger');
			console.error("updateOperationCommand - data : " + $scope.data);			
		});
	}
	
	/*
		Valid the balance
	*/
	$scope.validBalanceCommand = function()
	{
		//Check if all real amount are filled
		
		//Check if all operations are on "pointée" state
		$scope.operations.forEach(function(operation) 
		{
			if(operation.Status != 2)
			{
				//alert("Veuillez pointer toutes les opérations.");
			}
		});
		
		//Switch all operations on state "Archivée"
		$scope.operations.forEach(function(operation) 
		{
			//Call the service here
		});
		
		//Create the balance
	}
	
	/*
		Draw the pie charts
	*/
	$scope.drawChartCommand = function() 
	{
		console.info("drawChartCommand - called");
	
		var realCategories = [];
		var expectedCategories = [];
		realCategories.push(['Category', 'Total per category']);
		expectedCategories.push(['Category', 'Total per category']);

		$scope.categoryView.forEach(function(category) 
		{
			var realTotal = 0;
			var expectedTotal = 0;
			category.Operations.forEach(function(operation) 
			{
				realTotal += parseFloat(operation.Realamount);
				expectedTotal += parseFloat(operation.Expectedamount);
			});
			realCategories.push([ category.CategoryName, realTotal ]);
			expectedCategories.push([ category.CategoryName, expectedTotal ]);
		});
		
		var realData = google.visualization.arrayToDataTable(realCategories);
		var expectedData = google.visualization.arrayToDataTable(expectedCategories);
		var realOptions = 
		{
			title: 'Répartition des dépenses réelles'
		};
		var expectedOptions = 
		{
			title: 'Répartition des dépenses prévues'
		};

		var realChart = new google.visualization.PieChart(document.getElementById('pieTotalRealAmount'));
		var expectedChart = new google.visualization.PieChart(document.getElementById('pieTotalExpectedAmount'));
		realChart.draw(realData, realOptions);
		expectedChart.draw(expectedData, expectedOptions);
	}
	
	/*
		Update the operations
	*/
	$scope.synchronizeCategoriesAndFoldersCommand = function()
	{
		console.info("synchronizeCategoriesAndFoldersCommand - called");
		
		$scope.url = '../../Core/BonoHomeCore/Services/synchronizeCategoriesAndFoldersClient.php';

		console.info("synchronizeCategoriesAndFoldersCommand - call synchronizeCategoriesAndFoldersClient");
		
		$http.post($scope.url, { "idAccount": $scope.selectedaccount.Id}).
		success(function(data, status) 
		{
			console.info("synchronizeCategoriesAndFoldersCommand - call success"); 
			
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.setMessageCommand('Synchronisation des categories effectuée.', 'success');
			}
		})
		.
		error(function(data, status) 
		{
			console.info("synchronizeCategoriesAndFoldersCommand - call failed"); 
			$scope.data = data || "Request failed";
			$scope.status = status;			
			$scope.setMessageCommand('Synchronisation des categories en échec.', 'danger');
			console.error("synchronizeCategoriesAndFoldersCommand - data : " + $scope.data);			
		});
	}
	
	/*
	* Refresh accounts command
	*/
	$scope.refreshAccountsCommand = function()
	{
		console.info("refreshAccountsCommand - called");
		$http.post($scope.servicebase, { "service" : "getAccounts"}).
		success(function(data, status) 
		{
			console.info("refreshAccountsCommand - call success"); 
			$scope.status = status;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'danger');
			}
			else
			{
				$scope.accounts = data.response;
				
				if($scope.accounts.length > 0)
				{
					$scope.canSelectAccount = true;
				}
			}
		})
		.
		error(function(data, status) 
		{
			console.error("refreshAccountsCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;
			console.error("refreshAccountsCommand - data : " + $scope.data);		
		});
	}
	
	/*
	* The accounting loading process
	*/
	$scope.loadAccountingComponentCommand = function() 
	{
		//$("#jqxProgressBar").jqxProgressBar({ value: 0 });
		
		console.info("loadAccountingComponentCommand - called");
		
		//Set variables
		//$("#jqxProgressBar").jqxProgressBar({ value: 33 });
		console.info("Set default variables");
		$scope.accountStates = [];
		$scope.accountStates[0] = 'Inconnu';
		$scope.accountStates[1] = 'Ouvert';
		$scope.accountStates[2] = 'Fermé';
		
		$scope.operationStates = [];
		$scope.operationStates[0] = 'Inconnue';
		$scope.operationStates[1] = 'A venir';
		$scope.operationStates[2] = 'Pointée';
		$scope.operationStates[3] = 'Rejetée';
		$scope.operationStates[4] = 'Archivée';
		
		$scope.operationPaymentMeans = [];
		$scope.operationPaymentMeans[0] = 'Inconnu';
		$scope.operationPaymentMeans[1] = 'Carte bleue';
		$scope.operationPaymentMeans[2] = 'Chèque';
		$scope.operationPaymentMeans[3] = 'Virement';
		$scope.operationPaymentMeans[4] = 'Prélèvement';
		$scope.operationPaymentMeans[5] = 'Liquide';
		
		$scope.loadingAccounts = false;
		$scope.canSelectAccount = false;
		$scope.canAddAccount = true;
		$scope.canAddOperation = false;
		$scope.canAddCategory = false;
		$scope.canCreateBalance = false;
		$scope.canListOperations = false;
		$scope.credits = [];
		$scope.debits = [];
		$scope.expectedTotal = 0;
		$scope.realTotal = 0;
		$scope.canManageTree = true;
		$scope.selectedItem = '';
		$scope.isCategorySelected = false;
		$scope.selectedOperation = '';
		$scope.selectedView = 0;
		$scope.categories = [];
		$scope.categoryView = [];
		$scope.loadingCategories = false;
		$scope.accounts = [];
		$scope.Bill = null;

		//$("#jqxProgressBar").jqxProgressBar({ value: 66 });
		
		
		//$("#jqxProgressBar").jqxProgressBar({ value: 80 });
		$scope.refreshAccountsCommand();
		//$("#jqxProgressBar").jqxProgressBar({ value: 90 });
		$scope.setRangeDate();
		//$("#jqxProgressBar").jqxProgressBar({ value: 100 });
		
		$scope.isComponentLoading = false;
	}
	
	$scope.loadAccountingComponentCommand();
}]);